<template>
  <a-modal
    :open="visible"
    :title="`${provider?.providerName} - 开放授权配置`"
    width="95%"
    :footer="null"
    @cancel="handleClose"
    @update:open="$emit('update:visible', $event)"
    class="oauth-config-modal"
  >
    <div class="oauth-config-workspace">
      <!-- 左侧平台列表 -->
      <div class="platform-sidebar">
        <div class="sidebar-header">
          <h3>授权平台</h3>
        </div>

        <div class="platform-list">
          <div
            v-for="platform in platforms"
            :key="platform.key"
            class="platform-item"
            :class="{
              'active': selectedPlatform === platform.key
            }"
            @click="handlePlatformSelect(platform.key)"
          >
            <div class="platform-item-content">
              <div class="platform-basic">
                <img :src="platform.icon" :alt="platform.name" class="platform-icon" />
                <div class="platform-info">
                  <div class="platform-name">{{ platform.name }}</div>
                  <div class="platform-desc">{{ platform.description }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧配置详情 -->
      <div class="platform-detail">
        <div v-if="loading && !initialized" class="loading-state">
          <a-skeleton active :paragraph="{ rows: 8 }" />
        </div>

        <div v-else-if="!selectedPlatform" class="empty-state">
          <a-empty description="请选择要配置的平台" />
        </div>

        <div v-else-if="currentOAuthConfig" class="platform-detail-content">
          <div class="detail-header">
            <div class="platform-title">
              <img :src="selectedPlatformInfo?.icon" :alt="selectedPlatformInfo?.name" class="platform-icon" />
              <div>
                <h3>{{ selectedPlatformInfo?.name }}</h3>
                <p class="platform-desc">{{ selectedPlatformInfo?.description }}</p>
              </div>
            </div>


          </div>

          <!-- 配置表单 - 多Tab界面 -->
          <div class="config-form-container">
            <a-tabs v-model:activeKey="configActiveTab" type="card">
              <!-- 微信OAuth配置 -->
              <a-tab-pane key="wechat" tab="微信OAuth" v-if="selectedPlatform === 'wechat'">
                <a-form layout="vertical" :model="currentOAuthConfig">
                    <!-- 微信公众号配置 -->
                    <a-card title="微信公众号" size="small" style="margin-bottom: 16px;">
                      <a-row :gutter="16">
                        <a-col :span="12">
                          <a-form-item label="公众号AppID" required>
                            <a-input
                              v-model:value="currentOAuthConfig.wechatOAuth.mp.appId"
                              placeholder="请输入微信公众号AppID"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="公众号AppSecret" required>
                            <a-input-password
                              v-model:value="currentOAuthConfig.wechatOAuth.mp.appSecret"
                              placeholder="请输入微信公众号AppSecret"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="消息校验Token">
                            <a-input
                              v-model:value="currentOAuthConfig.wechatOAuth.mp.token"
                              placeholder="请输入消息校验Token"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="消息加解密密钥">
                            <a-input-password
                              v-model:value="currentOAuthConfig.wechatOAuth.mp.encodingAesKey"
                              placeholder="请输入消息加解密密钥"
                            />
                          </a-form-item>
                        </a-col>
                      </a-row>
                    </a-card>

                    <!-- 微信小程序配置 -->
                    <a-card title="微信小程序" size="small" style="margin-bottom: 16px;">
                      <a-row :gutter="16">
                        <a-col :span="12">
                          <a-form-item label="小程序AppID" required>
                            <a-input
                              v-model:value="currentOAuthConfig.wechatOAuth.miniapp.appId"
                              placeholder="请输入微信小程序AppID"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="小程序AppSecret" required>
                            <a-input-password
                              v-model:value="currentOAuthConfig.wechatOAuth.miniapp.appSecret"
                              placeholder="请输入微信小程序AppSecret"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="消息校验Token">
                            <a-input
                              v-model:value="currentOAuthConfig.wechatOAuth.miniapp.token"
                              placeholder="请输入消息校验Token"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="消息加解密密钥">
                            <a-input-password
                              v-model:value="currentOAuthConfig.wechatOAuth.miniapp.encodingAesKey"
                              placeholder="请输入消息加解密密钥"
                            />
                          </a-form-item>
                        </a-col>
                      </a-row>
                    </a-card>

                    <!-- 微信开放平台配置 -->
                    <a-card title="微信开放平台" size="small" style="margin-bottom: 16px;">
                      <a-row :gutter="16">
                        <a-col :span="12">
                          <a-form-item label="开放平台AppID" required>
                            <a-input
                              v-model:value="currentOAuthConfig.wechatOAuth.open!.appId"
                              placeholder="请输入微信开放平台AppID"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="开放平台AppSecret" required>
                            <a-input-password
                              v-model:value="currentOAuthConfig.wechatOAuth.open!.appSecret"
                              placeholder="请输入微信开放平台AppSecret"
                            />
                          </a-form-item>
                        </a-col>
                      </a-row>
                    </a-card>
                  </a-form>
              </a-tab-pane>

              <!-- 支付宝OAuth配置 -->
              <a-tab-pane key="alipay" tab="支付宝OAuth" v-if="selectedPlatform === 'alipay'">
                <a-form layout="vertical" :model="currentOAuthConfig">
                    <!-- 支付宝应用配置 -->
                    <a-card title="支付宝应用" size="small" style="margin-bottom: 16px;">
                      <a-row :gutter="16">
                        <a-col :span="24">
                          <a-form-item label="支付宝应用ID" required>
                            <a-input
                              v-model:value="currentOAuthConfig.alipayOAuth.app.appId"
                              placeholder="请输入支付宝应用ID"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="24">
                          <a-form-item label="应用私钥" required>
                            <a-textarea
                              v-model:value="currentOAuthConfig.alipayOAuth.app.privateKey"
                              placeholder="请输入应用私钥（RSA2格式）"
                              :rows="4"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="24">
                          <a-form-item label="支付宝公钥" required>
                            <a-textarea
                              v-model:value="currentOAuthConfig.alipayOAuth.app.alipayPublicKey"
                              placeholder="请输入支付宝公钥"
                              :rows="4"
                            />
                          </a-form-item>
                        </a-col>
                      </a-row>
                    </a-card>

                    <!-- 支付宝OAuth配置 -->
                    <a-card title="OAuth授权" size="small" style="margin-bottom: 16px;">
                      <a-row :gutter="16">
                        <a-col :span="12">
                          <a-form-item label="授权范围" required>
                            <a-select
                              v-model:value="currentOAuthConfig.alipayOAuth.oauth.scope"
                              mode="multiple"
                              placeholder="请选择授权范围"
                            >
                              <a-select-option value="auth_base">基础信息授权</a-select-option>
                              <a-select-option value="auth_user">用户信息授权</a-select-option>
                            </a-select>
                          </a-form-item>
                        </a-col>
                        <a-col :span="12">
                          <a-form-item label="回调地址" required>
                            <a-input
                              v-model:value="currentOAuthConfig.alipayOAuth.oauth.redirectUri"
                              placeholder="请输入OAuth回调地址"
                            />
                          </a-form-item>
                        </a-col>
                      </a-row>
                    </a-card>
                  </a-form>
              </a-tab-pane>

              <!-- 通用配置 -->
              <a-tab-pane key="common" tab="通用配置">
                <a-form layout="vertical" :model="currentOAuthConfig">
                    <a-card title="环境与安全设置" size="small" style="margin-bottom: 16px;">
                      <a-row :gutter="16">
                        <a-col :span="8">
                          <a-form-item label="环境配置" required>
                            <a-select
                              v-model:value="currentOAuthConfig.commonConfig.environment"
                            >
                              <a-select-option value="SANDBOX">
                                <span>沙箱环境</span>
                                <span style="color: #999; font-size: 12px; margin-left: 8px;">测试环境</span>
                              </a-select-option>
                              <a-select-option value="PRODUCTION">
                                <span>生产环境</span>
                                <span style="color: #999; font-size: 12px; margin-left: 8px;">正式环境</span>
                              </a-select-option>
                            </a-select>
                          </a-form-item>
                        </a-col>
                        <a-col :span="16">
                          <a-form-item label="回调域名" required>
                            <a-input
                              v-model:value="currentOAuthConfig.commonConfig.callbackDomain"
                              placeholder="请输入回调域名，如：https://your-domain.com"
                            />
                          </a-form-item>
                        </a-col>
                        <a-col :span="24">
                          <a-form-item label="加密密钥">
                            <a-input-password
                              v-model:value="currentOAuthConfig.commonConfig.encryptionKey"
                              placeholder="请输入加密密钥（可选）"
                            />
                          </a-form-item>
                        </a-col>
                      </a-row>
                    </a-card>
                  </a-form>
              </a-tab-pane>
            </a-tabs>
          </div>

          <!-- 固定保存按钮 -->
          <div class="fixed-save-button">
            <a-button
              type="primary"
              size="large"
              @click="handleSaveConfig"
              :loading="saving"
            >
              <template #icon>
                <SaveOutlined />
              </template>
              保存配置
            </a-button>
          </div>
        </div>

        <div v-else class="empty-state">
          <a-empty description="正在加载OAuth配置..." />
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { SaveOutlined } from '@ant-design/icons-vue'
import {
  mockGetProviderOAuthConfig,
  mockSaveProviderOAuthConfig
} from '@/mock/oauth-configs'
import { createDefaultOAuthConfig } from '@/mock/oauth-config-templates'
import type { ServiceProviderOAuthConfig } from '@/mock/oauth-config-types'
import type { ServiceProvider } from '@/mock/service-providers'

// Props
interface Props {
  visible: boolean
  provider?: ServiceProvider | null
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  provider: null
})

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'success': []
}>()

// 响应式数据
const currentOAuthConfig = ref<ServiceProviderOAuthConfig | null>(null)
const selectedPlatform = ref<string>('wechat')
const configActiveTab = ref<string>('wechat')
const saving = ref(false)
const loading = ref(false)
const initialized = ref(false)



// 平台列表
const platforms = [
  {
    key: 'wechat',
    name: '微信平台',
    description: '微信公众号、小程序、开放平台OAuth配置',
    icon: 'https://res.wx.qq.com/a/wx_fed/assets/res/OTE0YTAw.png'
  },
  {
    key: 'alipay',
    name: '支付宝平台',
    description: '支付宝开放平台OAuth配置',
    icon: 'https://tianyuankejioss.oss-cn-shanghai.aliyuncs.com/icon/alipay.svg'
  }
]

// 计算属性
const selectedPlatformInfo = computed(() => {
  return platforms.find(p => p.key === selectedPlatform.value)
})

// 方法
const handleClose = () => {
  emit('update:visible', false)
  currentOAuthConfig.value = null
  selectedPlatform.value = 'wechat'
  initialized.value = false
}

const handlePlatformSelect = (platformKey: string) => {
  selectedPlatform.value = platformKey
  configActiveTab.value = platformKey
}



const handleSaveConfig = async () => {
  if (!currentOAuthConfig.value) return

  saving.value = true
  try {
    await mockSaveProviderOAuthConfig(currentOAuthConfig.value)
    message.success('保存OAuth配置成功')
    emit('success')
  } catch (error) {
    message.error('保存OAuth配置失败')
  } finally {
    saving.value = false
  }
}



const loadOAuthConfig = async (providerId: string) => {
  loading.value = true
  try {
    const response = await mockGetProviderOAuthConfig(providerId)
    currentOAuthConfig.value = response.data
    initialized.value = true
  } catch (error) {
    // 如果没有找到配置，创建一个默认配置
    console.log('未找到OAuth配置，创建默认配置')
    currentOAuthConfig.value = createDefaultOAuthConfig(providerId, props.provider?.providerName || '')
    initialized.value = true
  } finally {
    loading.value = false
  }
}

// 监听provider变化
watch(
  () => props.provider,
  async (newProvider) => {
    if (newProvider && props.visible) {
      // 预设第一个平台，避免闪烁
      if (platforms.length > 0) {
        selectedPlatform.value = platforms[0].key
        configActiveTab.value = platforms[0].key
      }
      await loadOAuthConfig(newProvider.providerId)
    }
  },
  { immediate: true }
)

// 监听visible变化
watch(
  () => props.visible,
  async (visible) => {
    if (visible && props.provider) {
      // 预设第一个平台，避免闪烁
      if (platforms.length > 0) {
        selectedPlatform.value = platforms[0].key
        configActiveTab.value = platforms[0].key
      }
      await loadOAuthConfig(props.provider.providerId)
    } else if (!visible) {
      // 关闭时重置状态
      initialized.value = false
    }
  }
)
</script>

<style scoped>
/* OAuth配置工作区样式 */
.oauth-config-modal :deep(.ant-modal-body) {
  padding: 0;
}

.oauth-config-workspace {
  display: flex;
  height: 92vh;
  min-height: 800px;
  max-height: 1000px;
}

.platform-sidebar {
  width: 320px;
  border-right: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.platform-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.platform-item {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-bottom: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.platform-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.platform-item.active {
  border-color: #1890ff;
  background: #e6f7ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.platform-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.platform-basic {
  display: flex;
  align-items: center;
  flex: 1;
}

.platform-icon {
  width: 32px;
  height: 32px;
  object-fit: contain;
  margin-right: 12px;
}

.platform-info {
  flex: 1;
}

.platform-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.platform-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.platform-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-state {
  flex: 1;
  padding: 24px;
}

.platform-detail-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 24px;
  overflow: hidden;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.platform-title {
  display: flex;
  align-items: center;
}

.platform-title .platform-icon {
  width: 48px;
  height: 48px;
  margin-right: 16px;
}

.platform-title h3 {
  margin: 0 0 4px 0;
  font-size: 20px;
  color: #333;
}

.platform-title .platform-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}



.fixed-save-button {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.config-form-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 8px 80px 0;
}

.config-form-container::-webkit-scrollbar {
  width: 6px;
}

.config-form-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.config-form-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.config-form-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}






/* 响应式设计 */
@media (max-width: 1200px) {
  .oauth-config-workspace {
    flex-direction: column;
    height: auto;
  }

  .platform-sidebar {
    width: 100%;
    max-height: 300px;
  }

  .platform-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 8px;
  }

  .platform-item {
    margin-bottom: 0;
  }
}

@media (max-width: 768px) {
  .platform-item-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}
</style>